import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Popconfirm,
  message,
  Typography,
  Badge,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  CrownOutlined,
  SafetyCertificateOutlined,
  ReloadOutlined,
  SearchOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

import { usePlatformRoles, type PlatformRoleFormData } from '../../hooks/business';
import type { PlatformRole } from '../../types/platform';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const PlatformRolesPage: React.FC = () => {
  // 使用业务hooks
  const {
    roles,
    pagination,
    searchText,
    loading,
    error,
    loadRoles,
    createRole,
    updateRole,
    deleteRole,
    toggleRoleStatus,
    handleSearch,
    handlePageChange,
    refresh,
  } = usePlatformRoles();

  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<PlatformRole | null>(null);
  const [form] = Form.useForm();
  const [localSearchText, setLocalSearchText] = useState('');

  // 状态转换函数：后端数字状态 -> 前端字符串状态
  const convertStatusFromBackend = (status: number): 'active' | 'inactive' => {
    return status === 1 ? 'active' : 'inactive';
  };

  // 状态转换函数：前端字符串状态 -> 后端数字状态
  const convertStatusToBackend = (status: 'active' | 'inactive'): number => {
    return status === 'active' ? 1 : 0;
  };

  // 初始化加载交由usePlatformRoles内部的effect处理

  // 打开新增/编辑弹窗
  const openModal = (role?: PlatformRole) => {
    setEditingRole(role || null);
    setModalVisible(true);
    
    if (role) {
      form.setFieldsValue({
        ...role,
        status: convertStatusFromBackend(role.status as number),
      });
    } else {
      form.resetFields();
    }
  };

  // 关闭弹窗
  const closeModal = () => {
    setModalVisible(false);
    setEditingRole(null);
    form.resetFields();
  };

  // 保存角色
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const roleData: PlatformRoleFormData = {
        id: editingRole?.id,
        name: values.name,
        code: values.code,
        description: values.description,
        status: convertStatusToBackend(values.status),
        sort: values.sort,
      };

      if (editingRole) {
        await updateRole(editingRole.id, roleData);
        message.success('角色更新成功');
      } else {
        await createRole(roleData);
        message.success('角色创建成功');
      }
      
      closeModal();
      refresh();
    } catch (error) {
      console.error('保存角色失败:', error);
    }
  };

  // 删除角色
  const handleDeleteRole = async (roleId: string) => {
    try {
      await deleteRole(roleId);
      message.success('角色删除成功');
      refresh();
    } catch (error) {
      console.error('删除角色失败:', error);
    }
  };

  // 切换角色状态
  const handleToggleStatus = async (roleId: string, currentStatus: 'active' | 'inactive') => {
    try {
      const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
      await toggleRoleStatus(roleId, newStatus);
      message.success(`角色${newStatus === 'active' ? '启用' : '禁用'}成功`);
      refresh();
    } catch (error) {
      console.error('切换角色状态失败:', error);
    }
  };

  // 本地搜索处理
  const handleLocalSearch = () => {
    handleSearch(localSearchText);
  };

  // 表格列定义
  const columns: ColumnsType<PlatformRole> = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: PlatformRole) => (
        <Space>
          {record.isBuiltin ? (
            <CrownOutlined style={{ color: '#faad14' }} />
          ) : (
            <UserOutlined style={{ color: '#1890ff' }} />
          )}
          <Text strong>{text}</Text>
          {record.isBuiltin && <Tag color="gold">内置</Tag>}
        </Space>
      ),
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
      render: (text: string) => <Text code>{text}</Text>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number, record: PlatformRole) => {
        const isActive = status === 1;
        return (
          <Switch
            checked={isActive}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            onChange={() => handleToggleStatus(record.id, isActive ? 'active' : 'inactive')}
            disabled={record.isBuiltin}
          />
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record: PlatformRole) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            onClick={() => openModal(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => openModal(record)}
            disabled={record.isBuiltin}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDeleteRole(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
              disabled={record.isBuiltin}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 页面标题与操作区（统一样式） */}
      <div
        style={{
          marginBottom: 24,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '0 4px',
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <SafetyCertificateOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            平台角色管理
          </Title>
          <Text type="secondary" style={{ fontSize: 14, marginTop: 4, display: 'block' }}>
            管理平台级别的角色权限，内置角色不可删除
          </Text>
        </div>
        <Space>
          <Input.Search
            placeholder="搜索角色名称或编码"
            allowClear
            style={{ width: 240 }}
            onSearch={handleLocalSearch}
            value={localSearchText}
            onChange={(e) => setLocalSearchText(e.target.value)}
            prefix={<SearchOutlined />}
          />
          <Button
            icon={<ReloadOutlined />}
            onClick={refresh}
            style={{ borderColor: '#d9d9d9', color: '#666' }}
          >
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openModal()}>
            新增角色
          </Button>
        </Space>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: handlePageChange,
            onShowSizeChange: handlePageChange,
          }}
        />
      </Card>

      {/* 新增/编辑角色弹窗 */}
      <Modal
        title={editingRole ? '编辑角色' : '新增角色'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={closeModal}
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: true,
            sort: 10,
          }}
        >
          <Form.Item
            name="code"
            label="角色编码"
            rules={[
              { required: true, message: '请输入角色编码' },
              { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线' },
            ]}
          >
            <Input placeholder="如：PLATFORM_ADMIN" disabled={!!editingRole?.isBuiltin} />
          </Form.Item>

          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="如：平台管理员" />
          </Form.Item>

          <Form.Item
            name="description"
            label="角色描述"
          >
            <TextArea 
              placeholder="描述此角色的职责和权限范围"
              rows={3}
            />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序号' }]}
            initialValue={10}
          >
            <Input type="number" placeholder="数字越小排序越前" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PlatformRolesPage;